/**
 * Created by jiachenpan on 16/11/18.
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (("" + time).length === 10) time = parseInt(time) * 1000;
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === "a")
      return ["一", "二", "三", "四", "五", "六", "日"][value - 1];
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

export function formatTime(time, option) {
  time = +time * 1000;
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

// 格式化时间
export function getQueryObject(url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf("?") + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

//时间比较（yyyy-MM-dd）
export function compareDate(startDate, endDate) {
  var arrStart = startDate.split("-");
  var startTime = new Date(arrStart[0], arrStart[1], arrStart[2]);
  var startTimes = startTime.getTime();
  var arrEnd = endDate.split("-");
  var endTime = new Date(arrEnd[0], arrEnd[1], arrEnd[2]);
  var endTimes = endTime.getTime();
  if (endTimes < startTimes) {
    alert("结束时间不能小于开始时间");
    return false;
  }
  return true;
}

//获得两个日期之间相差的天数
export function getDaysBetweenTwoDates(date1, date2) {
  var date1Str = date1.split("-"); //将日期字符串分隔为数组,数组元素分别为年.月.日
  //根据年 . 月 . 日的值创建Date对象
  var date1Obj = new Date(date1Str[0], date1Str[1] - 1, date1Str[2]);
  var date2Str = date2.split("-");
  var date2Obj = new Date(date2Str[0], date2Str[1] - 1, date2Str[2]);
  var t1 = date1Obj.getTime();
  var t2 = date2Obj.getTime();
  var dateTime = 1000 * 60 * 60 * 24; //每一天的毫秒数
  var minusDays = Math.floor((t2 - t1) / dateTime); //计算出两个日期的天数差
  var days = Math.abs(minusDays); //取绝对值
  return days;
}

/**
 *日期 加一天
 * @param {String,Date,timeStamp} date 日期
 * @param {String,Num} days 变化的天数
 */
export function addDate(date, days) {
  function getFormatDate(arg) {
    if (arg == undefined || arg == "") {
      return "";
    }
    var re = arg + "";
    if (re.length < 2) {
      re = "0" + re;
    }
    return re;
  }
  if (days == undefined || days == "") {
    days = 1;
  }
  var date = new Date(date);
  date.setDate(date.getDate() + days);
  var month = date.getMonth() + 1;
  var day = date.getDate();
  return (
    date.getFullYear() + "-" + getFormatDate(month) + "-" + getFormatDate(day)
  );
}

/**
 *get getByteLen
 * @param {Sting} val input value
 * @returns {number} output value
 */
export function getByteLen(val) {
  let len = 0;
  for (let i = 0; i < val.length; i++) {
    if (val[i].match(/[^\x00-\xff]/gi) != null) {
      len += 1;
    } else {
      len += 0.5;
    }
  }
  return Math.floor(len);
}

export function cleanArray(actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

export function param(json) {
  if (!json) return "";
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return "";
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    })
  ).join("&");
}

export function param2Obj(url) {
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  );
}

export function html2Text(val) {
  const div = document.createElement("div");
  div.innerHTML = val;
  return div.textContent || div.innerText;
}

export function objectMerge(target, source) {
  /* Merges two  objects,
     giving the last one precedence */

  if (typeof target !== "object") {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  for (const property in source) {
    if (source.hasOwnProperty(property)) {
      const sourceProperty = source[property];
      if (typeof sourceProperty === "object") {
        target[property] = objectMerge(target[property], sourceProperty);
        continue;
      }
      target[property] = sourceProperty;
    }
  }
  return target;
}

export function scrollTo(element, to, duration) {
  if (duration <= 0) return;
  const difference = to - element.scrollTop;
  const perTick = (difference / duration) * 10;
  setTimeout(() => {
    element.scrollTop = element.scrollTop + perTick;
    if (element.scrollTop === to) return;
    scrollTo(element, to, duration - 10);
  }, 10);
}

export function toggleClass(element, className) {
  if (!element || !className) {
    return;
  }
  let classString = element.className;
  const nameIndex = classString.indexOf(className);
  if (nameIndex === -1) {
    classString += "" + className;
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

export function hasClass(obj, cls) {
  return obj.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

export function addClass(obj, cls) {
  function hasClass(obj, cls) {
    return obj.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
  }
  if (!hasClass(obj, cls)) {
    obj.className += " " + cls;
  }
}

export function removeClass(obj, cls) {
  function hasClass(obj, cls) {
    return obj.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
  }
  if (hasClass(obj, cls)) {
    var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    obj.className = obj.className.replace(reg, " ");
  }
}

export const pickerOptions = [
  {
    text: "今天",
    onClick(picker) {
      const end = new Date();
      const start = new Date(new Date().toDateString());
      end.setTime(start.getTime());
      picker.$emit("pick", [start, end]);
    }
  },
  {
    text: "最近一周",
    onClick(picker) {
      const end = new Date(new Date().toDateString());
      const start = new Date();
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 7);
      picker.$emit("pick", [start, end]);
    }
  },
  {
    text: "最近一个月",
    onClick(picker) {
      const end = new Date(new Date().toDateString());
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      picker.$emit("pick", [start, end]);
    }
  },
  {
    text: "最近三个月",
    onClick(picker) {
      const end = new Date(new Date().toDateString());
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      picker.$emit("pick", [start, end]);
    }
  }
];

export function getTime(type) {
  if (type === "start") {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function(...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

export function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "shallowClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  for (const keys in source) {
    if (source.hasOwnProperty(keys)) {
      if (source[keys] && typeof source[keys] === "object") {
        targetObj[keys] = source[keys].constructor === Array ? [] : {};
        targetObj[keys] = deepClone(source[keys]);
      } else {
        targetObj[keys] = source[keys];
      }
    }
  }
  return targetObj;
}

// 过滤HTML标签
export function filterHTMLTag(msg) {
  var msg = msg.replace(/<\/?[^>]*>/g, ""); //去除HTML Tag
  msg = msg.replace(/[|]*\n/, ""); //去除行尾空格
  // msg = msg.replace(/&npsp;/gi, ""); //去掉npsp
  msg = msg.replace(/[ ]|[&nbsp;]|[&mdash;]/g, "");
  msg = msg.replace(/lquo/g, "“");
  msg = msg.replace(/rquo/g, "”");
  return msg;
}

// 获取子节点
export function childrenEle(curEle, tagName) {
  var nodeList = curEle.childNodes;
  var ary = [];
  if (/MSIE(6|7|8)/.test(navigator.userAgent)) {
    for (var i = 0; i < nodeList.length; i++) {
      var curNode = nodeList[i];
      if (curNode.nodeType === 1) {
        ary[ary.length] = curNode;
      }
    }
  } else {
    ary = Array.prototype.slice.call(curEle.children);
  }

  // 获取指定子元素
  if (typeof tagName === "string") {
    for (var k = 0; k < ary.length; k++) {
      curTag = ary[k];
      if (curTag.nodeName.toLowerCase() !== tagName.toLowerCase()) {
        ary.splice(k, 1);
        k--;
      }
    }
  }
  return ary;
}

/**
 * 平滑滚动  基于scrollTo
 * @param {numeber} currentY 需要移动的dom当前位置离网页顶端的距离
 * @param {number} targetY 需要移动的dom当前位置离要移到的位置的距离
 */
export function scroll(currentY, targetY) {
  // 计算需要移动的距离
  let needScrollTop = targetY - currentY;
  let _currentY = currentY;
  setTimeout(() => {
    // 一次调用滑动帧数，每次调用会不一样
    const dist = Math.ceil(needScrollTop / 10);
    _currentY += dist;
    window.scrollTo(_currentY, currentY);
    // 如果移动幅度小于十个像素，直接移动，否则递归调用，实现动画效果
    if (needScrollTop > 10 || needScrollTop < -10) {
      scroll(_currentY, targetY);
    } else {
      window.scrollTo(_currentY, targetY);
    }
  }, 1);
}

/**
 * 判断IE版本
 */
export function IEVersion() {
  var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  var isIE =
    userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
  var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
  var isIE11 =
    userAgent.indexOf("Trident") > -1 && userAgent.indexOf("rv:11.0") > -1;
  if (isIE) {
    var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
    reIE.test(userAgent);
    var fIEVersion = parseFloat(RegExp["$1"]);
    if (fIEVersion == 7) {
      return 7;
    } else if (fIEVersion == 8) {
      return 8;
    } else if (fIEVersion == 9) {
      return 9;
    } else if (fIEVersion == 10) {
      return 10;
    } else {
      return 6; //IE版本<=7
    }
  } else if (isEdge) {
    return "edge"; //edge
  } else if (isIE11) {
    return 11; //IE11
  } else {
    return -1; //不是ie浏览器
  }
}

// 定义请求接口的地址。
// export const rootsUrl = [
//   "http://www.fastersoft.com.cn:85", // 网站后台
//   "http://www.fastersoft.com.cn:83", //学习 活动
//   "http://www.fastersoft.com.cn:1520", //票务
//   "http://www.fastersoft.com.cn:85", // 文创
//   "http://www.fastersoft.com.cn:99" // OA
// ];

// 临时服务器
// export const rootsUrl = [
//   "http://211.159.187.81:8081", // 网站后台
//   "http://211.159.187.81:8082", //学习 活动
//   "http://211.159.187.81:8082", //票务
//   "http://211.159.187.81:8081", // 文创
//   "http://211.159.187.81:99" // OA
// ];

// 博物馆内网环境接口
// export const rootsUrl = [
//   "http://172.16.102.18:8088", // 网站后台
//   "http://172.16.102.19:8082", // 学习 活动
//   "http://172.16.102.19:8081", // 票务
//   "http://172.16.102.19:8082", // 文创众筹
//   "http://172.16.102.18:8077" // OA
// ];

// 与张乐联调
// export const rootsUrl = [
//   "http://211.159.187.81:8081", // 网站后台
//   "http://192.168.0.13:8080", //学习 活动
//   "http://211.159.187.81:8082", //票务
//   "http://211.159.187.81:8081", // 文创
//   "http://211.159.187.81:99" // OA
// ];

// 外网访问地址
// export const rootsUrl = [
//   "http://new.csm.hn.cn:8088", // 网站后台
//   "http://183.215.42.2:8082", // 学习 活动
//   "http://183.215.42.2:8081", // 票务
//   "http://183.215.42.2:8082", // 文创众筹
//   "http://183.215.42.2:8078" // OA
// ];

// 2018年9月4日  更正地址 正式发布
export const rootsUrl = [
  "http://www.csm.hn.cn", // 网站后台
  "http://111.8.37.194:8082", // 学习 活动
  "http://111.8.37.194:8081", // 票务
  "http://111.8.37.194:8082", // 文创众筹
  "http://111.8.37.194:8077" // OA111.8.37.194:8077
  // "http://211.159.187.81:98" //OA测试
];

// 本地联调接口的地址。
// export const rootsUrl = [
//   "http://www.fastersoft.com.cn:85", // 网站后台
//   "http://www.fastersoft.com.cn:83", //学习 活动
//   "http://www.fastersoft.com.cn:1520", //票务
//   "http://192.168.0.28:8080", // 文创
//   "http://www.fastersoft.com.cn:99", // OA
//   "http://192.168.0.195:8080", //璧莹
//   "http://192.168.0.28:8080", //zl
//   "http://192.168.0.138:8083", //康宝
//   "http://192.168.0.72:8081" //xiaoQiang
// ];
